package com.longrise.android.byjk.plugins.dealsituation.course.video2.education.insurance;

import android.content.Intent;
import android.text.TextUtils;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.common.UrlConstants;
import com.longrise.android.byjk.event.CourseDetailEvent;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.android.byjk.plugins.course.coursedetail.videoexercises.VideoExercisesActvity;
import com.longrise.android.byjk.plugins.dealsituation.course.cache.AssistCache;
import com.longrise.android.byjk.plugins.dealsituation.course.cache.CourseCache;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.defend.DefendStudy;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.params.StudyRecordBase;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.params.ToDispatchStudy;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.params.VideoConsts;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.params.VideoParams;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.study.DefendHandler;
import com.longrise.common.base.BasePresenter;
import com.longrise.common.datasource.remote.LoadDataManager;
import com.longrise.common.utils.PrintLog;

import org.greenrobot.eventbus.EventBus;

/**
 * Created by godliness on 2017/8/22.
 */

public class InsurancePresenter extends BasePresenter<InsuranceView> implements DefendStudy.DefendStudyCallback {

    private final static String TAG = "InsurancePresenter";

    /**
     * 当前播放断点
     */
    public int mResumePos;

    /**
     * mNoPassSize > 0 && mPreformCompleted==true
     */
    private int mNoPassSize;
    private boolean mPreformCompleted;

    /**
     * 维护过程记录
     */
    private DefendStudy mDefendStudy;
    private int mDuration;

    private VideoParams mParams;

    /**
     * 是否finished
     */
    private boolean mFinished;
    //视频是否通过
    public boolean mIsvideopass;

    public void setFinished() {
        mFinished = true;
    }

    public InsurancePresenter() {
        initDefendStudy();
    }

    @Override
    protected void init() {
    }

    /**
     * @param duration 视频总时长
     */
    public void monitorDefendStudy(int duration) {
        this.mDuration = duration;
        if (mDefendStudy != null) {
            mDefendStudy.monitor();
        }
    }

    public void startDefendStudy() {
        if (mDefendStudy != null) {
            mDefendStudy.start();
        }
    }

    public void preformStart() {
        if (mDefendStudy != null) {
            mDefendStudy.manualPreformStart();
        }
    }

    public void stopDefendStudy() {
        DefendHandler.getInstance().stop();
    }

    /**
     * 避免无谓课程详情页刷新数据
     * 退出播放器时，根据条件通知课程详情刷新【课程】状态
     */
    public void sendMessage() {
        if (mPreformCompleted && mNoPassSize > 0) {

            CourseDetailEvent event = new CourseDetailEvent();
            event.setRefreshDetail(true);
            EventBus.getDefault().post(event);
        }
    }

    /**
     * 课后习题
     */
    public void toQa() {
        if (mParams == null) {
            return;
        }
        Intent intent = new Intent(mContext, VideoExercisesActvity.class);
        intent.putExtra(VideoExercisesActvity.COURSEBEAN, mParams);
        mContext.startActivity(intent);
        mView.onBack();
    }


    public void toStartNormalVideo(VideoParams videoParams){
        this.mParams = videoParams;
        mView.showLoadingDialog();
        if (mParams != null) {
            mParams.mFinish = true;
            mParams.mVideopass = true;
            mParams.mHasqa = false;
            mIsvideopass = true; //告诉controller 视频已经通过
        }
        mView.parseVideoInfor(mParams.mVideoPath);
    }

    /**
     * 请求课件地址
     */
    public void toRequest(VideoParams videoParams) {
        this.mParams = videoParams;
        mView.showLoadingDialog();
        EntityBean bean = new EntityBean();
        bean.set("cardno", UserInfor.getInstance().getUsersfzh());
        bean.set("courseid", mParams.mCourseId);
        bean.set("studentno", mParams.mStudentNo);
        bean.set("cwid", mParams.mCwid);
        bean.set("pathno", mParams.mPathNo);
        bean.set("isdownload", "2");  //非下载
        bean.set("comfrom", "Android");
        EntityBean reqBean = new EntityBean();
        reqBean.set("bean", bean);
        LoadDataManager.getInstance().callService(null, UrlConstants.BaseUrl, "bbt_course_getVideoData", reqBean, mCallListener);
    }

    /**
     * 课后习题逻辑
     */
    public void exerciseOptions(VideoParams params) {
        if (params == null) {
            return;
        }
        boolean hasqa = params.mHasqa;
        if (!hasqa) { //没有课后习题
            return;
        }
        boolean isFinish = params.mFinish;
        if (isFinish) {  //立即查看课后习题
            mView.hasqa();
            return;
        }
        boolean videopass = params.mVideopass;
        if (videopass) {  //立即做课后习题
            mView.hasqa();
        }
        //播放
    }

    /**
     * to学历教育课件
     */
    public void toStudyStart(VideoParams params) {
        if (params == null) {
            return;
        }
        Class<?> clz = ToDispatchStudy.dispatchStudyStart(params.mCwidStyle);
        toStudyStart(clz, params);
    }

    private void toStudyStart(Class clz, VideoParams videoParams) {
        if (clz == null) {
            return;
        }
        Intent videoIntent = new Intent(mContext, clz);
        videoIntent.putExtra(VideoConsts.VIDEO_PARAMS_PARCELABLE, videoParams);
        mContext.startActivity(videoIntent);
        mView.onBack();
    }

    private LoadDataManager.OnRequestCallListener mCallListener = new LoadDataManager.OnRequestCallListener() {
        @Override
        public void onSuccess(String key, String service, Object result) {
            if (mFinished) {
                return;
            }
            if (!(result instanceof EntityBean)) {
                mView.showToast("数据结构异常");
                mView.onError();
                return;
            }
            EntityBean resultBean = (EntityBean) result;
            int resultstate = resultBean.getInt("resultstate");
            if (resultstate != 1) {
                mView.showToast(resultBean.getString("resultdesc"));
                mView.onError();
                return;
            }
            try {
                parse(resultBean.getBean("result"));
            } catch (Exception e) {
                mView.onError();
                e.printStackTrace();
            }
        }

        @Override
        public void onError(String key, String service, Throwable ex, boolean isOnCallback) {
            mView.onError();
        }

        @Override
        public void onFinished(String key, String service) {

        }
    };

    private void parse(EntityBean bean) {
        String videopath = bean.getString("videourl", "");
        String recordid = bean.getString("recordid", "");
        String position = bean.getString("position", "0");
        boolean isFinish = bean.getBoolean("isfinish", false);
        mIsvideopass = bean.getBoolean("isvideopass", false);
        boolean ishasqa = bean.getBoolean("ishasqa", false);
        try {
            mResumePos = Integer.parseInt(position);
        } catch (Exception e) {
            mResumePos = 0;
        }
        if (!isFinish && !mIsvideopass) {
            mNoPassSize++;
        }
        if (strIsEmpty(recordid)) {
            mView.showToast("课件学习记录异常");
            mView.onError();
            return;
        }
        if (strIsEmpty(videopath)) {
            mView.showToast("课件配置节点异常");
            mView.onError();
            return;
        }
        PrintLog.e(TAG, "recordid: " + recordid + " isFinish: " + isFinish + " isvideopass: " + mIsvideopass + " ishasqa: " + ishasqa);
        setCurrentCwid(videopath, recordid, isFinish, mIsvideopass, ishasqa);
    }

    /**
     * 更新当前课信息
     */
    private void setCurrentCwid(String videopath, String recordid, boolean isFinish, boolean isvideopass, boolean ishasqa) {
        if (mParams != null) {
            mParams.recordid = recordid;
            mParams.mFinish = isFinish;
            mParams.mVideopass = isvideopass;
            mParams.mHasqa = ishasqa;

        }
        mView.parseVideoInfor(videopath);
        //课后习题逻辑
        exerciseOptions(mParams);
    }

    private boolean strIsEmpty(String pams) {
        return TextUtils.isEmpty(pams);
    }

    /**
     * 维护过程回调
     */
    private void initDefendStudy() {
        mDefendStudy = new DefendStudy();
        mDefendStudy.setStudyCallback(this);
    }

    /**
     * 避免【课程】详情无谓刷新
     * 通过该比较方式，用于确认当前存在已学习完成的【课件】，
     * 退出播放器时，根据该参数决定课程详情是否toRefrush()，
     */
    private void recordStateChange() {
        if (mParams == null) {
            return;
        }
        boolean currentCwidBeforeState = mParams.mVideopass;
        if (mNoPassSize > 0 && !currentCwidBeforeState) {
            mPreformCompleted = true;
        }
    }

    /**
     * 避免【课程】详情无谓数据刷新
     * 确认当前是否完成，如果当前课件在播放之前是已通过状态，不做任何处理
     * 条件1：当前【课件】之前状态为未通过，
     * 条件2：当前【课件】不存在课后习题
     */
    private void updateCwidState() {
        if (mParams == null) {
            return;
        }
        boolean upLoaded = false;
        boolean videoPass = mParams.mVideopass;
        boolean hasqa = mParams.mHasqa;
        if (!videoPass && !hasqa) {
            upLoaded = true;
        }
        if (upLoaded) {
            sendUpdateMessage();
        }
        //必须最后更新当前课件通过状态
        mParams.mVideopass = true;
    }

    /**
     * 更新课程详情页对应【课件】状态
     * 首先更新已缓存课件学习状态，如果更新失败通知课程详情页toRefrush()
     * 否则通知课程详情页根据索引位置更新课件状态
     */
    private void sendUpdateMessage() {
        if (mParams.mCwidLocal == null) {
            //如果在课程详情页进入，该值为null，不发送消息
            return;
        }
        //更新已缓存课件状态
        boolean cacheUpdated = AssistCache.updateCwidStateInCache(mParams.mCourseId, mParams.mCwidLocal);
        if (cacheUpdated) {
            //如果更新成功通知课程详情页根据索引位置更新课件状态
            CourseDetailEvent event = new CourseDetailEvent();
            event.setCoursePosition(mParams.mCwidLocal);
            EventBus.getDefault().post(event);
        } else {
            //如果更新失败，直接通知课程详情页toRefrush()
            CourseDetailEvent event = new CourseDetailEvent();
            event.setRefreshDetail(true);
            EventBus.getDefault().post(event);
        }
        //使内存缓存无效
        CourseCache.contains("");
    }

    /**
     * 维护过程所需参数
     */
    private StudyRecordBase.Record genratorRecord() {
        if (mParams != null && mView.isPrepared()) {
            StudyRecordBase.Record record = StudyRecordBase.getRecordInstance();
            record.mCourseid = mParams.mCourseId;
            record.mCwid = mParams.mCwid;
            record.mPathno = mParams.mPathNo;
            record.mStudentno = mParams.mStudentNo;
            record.mId = mParams.recordid;
            return record;
        }
        return null;
    }

    /**
     * ----------------------------维护过程记录---------------------------------------
     * 维护过程记录 所需参数
     */
    @Override
    public StudyRecordBase.Record getRecord() {
        StudyRecordBase.Record record = genratorRecord();
        if (record == null) {
            //不做任何执行
            return null;
        }
        int position = mView.getCurrentPosition();
        if (position > mDuration) {
            mDuration = mView.getDuration();
        }
        if (position > mDuration) {
            mDuration = position;
        }
        record.mPosition = position;
        record.mDuration = mDuration;
        return record;
    }

    /**
     * 维护过程记录
     *
     * @param videopass 是否通过
     */
    @Override
    public void onDefend(boolean videopass) {
        mResumePos = mView.getCurrentPosition();

        if (videopass) {
            recordStateChange();
            mView.defendSuccess();
            updateCwidState();
        }
    }

    /**
     * 维护过程记录
     *
     * @param errorType 出错类型
     */
    @Override
    public void onError(int errorType) {
        mView.defendError(errorType);
    }
}
